package com.esheeper.logictimestampprovider.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.scripting.support.ResourceScriptSource;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Configuration
public class RedisScriptConfig {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Bean
    public DefaultRedisScript<Long> deductStockRedisScript() {
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        //我这里的路径是resource  下的 lua 文件下的 .lua文件
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("lua/Atomic.lua")));
        redisScript.setResultType(Long.class);
        loadRedisScript(redisScript, "Atomic.lua");
        return redisScript;
    }

    /**
     * 加载lua脚本到redis服务器
     * @param redisScript
     * @param luaName
     */
    private void loadRedisScript(DefaultRedisScript<Long> redisScript, String luaName) {
        try {
            List<Boolean> results = stringRedisTemplate.getConnectionFactory().getConnection().scriptExists(redisScript.getSha1());
            if (Boolean.FALSE.equals(results.get(0))) {
                String sha = stringRedisTemplate.getConnectionFactory().getConnection().scriptLoad(scriptBytes(redisScript));
                log.info("预加载lua脚本成功：{}, sha=[{}]", luaName, sha);
            }
        } catch (Exception e) {
            log.error("预加载lua脚本异常：{}", luaName, e);
        }
    }

    /**
     * 序列化lua脚本
     * @param script
     * @return
     */
    private byte[] scriptBytes(RedisScript<?> script) {
        return this.stringRedisTemplate.getStringSerializer().serialize(script.getScriptAsString());
    }


}
